<template>
  <div>
    <ex-dialog width="1000px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose"
      :closeOnClickModal="false">
      <el-form ref="form" :model="ruleForm" :rules="rules" label-width="140px" :disabled="status==1?true:false">
        <el-form-item label="结算方式:" prop="settleBankType">
          <el-select filterable v-model="ruleForm.settleBankType" placeholder="请选择">
            <el-option v-for="item in settleMethodLs" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="银行预留手机号:" prop="bankPhone">
          <el-input v-model="ruleForm.bankPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="结算账户名称:" prop="bankAccountName">
          <el-input v-model="ruleForm.bankAccountName" placeholder="请输入" />
        </el-form-item>
        <!-- 对法人私卡 -->
        <template v-if="ruleForm.settleBankType==2">
          <el-form-item label="结算银行卡正面:" prop="bankCardFront" ref="bankCardFrontRef">
            <ImageUploadMore :limit="1" :fileSize="20" @successImg="getBankCardFront" :value="ruleForm.bankCardFront">
            </ImageUploadMore>
          </el-form-item>
          <el-form-item label="结算银行卡背面:" prop="bankCardBack" ref="bankCardBackRef">
            <ImageUploadMore :limit="1" :fileSize="20" @successImg="getBankCardBack" :value="ruleForm.bankCardBack">
            </ImageUploadMore>
          </el-form-item>
          <el-form-item label="结算银行卡号:" prop="bankNo">
            <el-input type="text" v-model="ruleForm.bankNo" placeholder="请输入" />
          </el-form-item>
        </template>
        <!-- 对公 -->
        <template v-if="ruleForm.settleBankType==1">
          <el-form-item label="开户行许可证:" prop="licence" ref="licenceRef">
            <ImageUploadMore :limit="1" :fileSize="20" @successImg="getLicence" :value="ruleForm.licence">
            </ImageUploadMore>
          </el-form-item>
          <el-form-item label="开户行卡号:" prop="bankNo">
            <el-input type="text" v-model="ruleForm.bankNo" placeholder="请输入" />
          </el-form-item>
        </template>
        <el-form-item label="开户行名称:" prop="bankName">
          <el-input type="text" v-model="ruleForm.bankName" placeholder="请输入"
            :disabled="ruleForm.bankRegionAvalue.length==0?false:true" />
          <el-tooltip class="item" effect="dark" content="如需更改开户行，请先删除银行地区" placement="top-start"
            v-if="ruleForm.bankRegionAvalue.length!=0">
            <div class="el-icon-question" style="color: red;margin-left: 10px;cursor: pointer"></div>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="银行地区:" prop="bankRegionAvalue" ref="bankRegionAvalueRef">
          <el-cascader :options="regionOptions" :props="{ value: 'id',label: 'label',children: 'children'}" filterable
            @change="bankRegionChange" v-model="ruleForm.bankRegionAvalue" clearable style="width: 300px">
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属支行名称:" prop="bankCode">
          <el-select filterable v-model="ruleForm.bankCode" placeholder="请选择" @change="branchChanges"
            v-loading="bankLoading" element-loading-text="支行加载中" element-loading-spinner="el-icon-loading">
            <el-option v-for="item in openAccBankLs" :key="item.bankCode" :label="item.bankName"
              :value="item.bankCode" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="status==''">提交变更申请</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="status==3">重新提交变更申请</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </ex-dialog>
  </div>

</template>
<script>
  import {
    getBankCity,
    getBankBranch,
    fundChangeSettle,
    getFundChangeSettle,
    updateFundChangeSettle,
  } from "@/api/merchants";
  import {
    array
  } from 'jszip/lib/support';
  export default {
    props: {
      //   visible: Boolean,
      //   id: String,
      //   pathType: String,
    },
    components: {

    },
    data() {
      return {
        visible: false,
        fundAccountId: '', //
        type: '', //类型 1：日常消费  2： 存管账户
        status: '', //1 审核中 3: 失败  ''：申请
        refusedDialog: false,
        title: '',
        submitLoading: false,
        bankLoading: false, //支行loading
        settleMethodLs: [], //结算方式字典
        regionOptions: [], //银行城市
        openAccBankLs: [], //支行
        ruleForm: {
          bankRegionAvalue: [], //城市选择
          bankAccountName: '', //结算账户名称
          bankCardBack: '', //银行卡背面
          bankCardFront: '', //银行卡正面
          bankCity: '', //开户行城市
          bankCode: '', //开户支行code
          bankName: '', //开户行名称
          bankNo: '', //结算卡号
          bankPhone: '', //银行预留手机号
          bankProvince: '', //开户行省份
          bankSubName: '', //开户支行名称
          fundAccountId: '', //资金帐号id
          id: '', //id，更新的时候传
          licence: '', //开户许可证
          settleBankType: '', //1 对公 2 对法人私
        },
        rules: {
          settleBankType: [{
            required: true,
            message: '请选择结算方式',
            trigger: ['change', 'blur']
          }, ],
          bankPhone: [{
            required: true,
            message: '请输入银行预留手机号',
            trigger: ['change', 'blur']
          }, ],
          bankAccountName: [{
            required: true,
            message: '请输入结算账户名称',
            trigger: ['change', 'blur']
          }, ],
          bankCardFront: [{
            required: true,
            message: '请上传结算银行卡正面',
            trigger: ['change', 'blur']
          }, ],
          bankCardBack: [{
            required: true,
            message: '请上传结算银行卡背面',
            trigger: ['change', 'blur']
          }, ],
          licence: [{
            required: true,
            message: '请上传开户许可证',
            trigger: ['change', 'blur']
          }, ],
          bankNo: [{
            required: true,
            message: '请输入卡号',
            trigger: ['change', 'blur']
          }, ],
          bankName: [{
            required: true,
            message: '请输入开户行名称',
            trigger: ['change', 'blur']
          }, ],
          bankCode: [{
            required: true,
            message: '请选择所属支行名称',
            trigger: ['change', 'blur']
          }, ],
          bankRegionAvalue: [{
            required: true,
            message: '请选择银行地区',
            trigger: ['change']
          }, ],
        }
      }
    },
    watch: {},
    created() {

    },
    methods: {
      open(id, type, status) {
        console.log('id=', id, 'type=', type, 'status=', status)
        this.fundAccountId = id
        this.type = type
        this.status = status
        this.reset()
        if (this.type == 1 && this.status == 1) {
          this.title = '日常消费账户结算信息变更（审核中）'
        } else if (this.type == 1 && this.status == 3) {
          this.title = '日常消费账户结算信息变更（失败）'
        } else if (this.type == 1 && this.status == '') {
          this.title = '日常消费账户结算信息变更（非接口）'
        } else if (this.type == 2 && this.status == 1) {
          this.title = '存管账户结算信息变更（审核中）'
        } else if (this.type == 2 && this.status == 3) {
          this.title = '存管账户结算信息变更（失败）'
        } else if (this.type == 2 && this.status == '') {
          this.title = '存管账户结算信息变更（非接口）'
        }
        this.visible = true
        this.getAdminDict()
        this.getBankCitys()
        this.getDetail()
      },
      // 表单重置
      reset() {
        this.ruleForm = {
          bankRegionAvalue: [], //城市选择
          bankAccountName: '', //结算账户名称
          bankCardBack: '', //银行卡背面
          bankCardFront: '', //银行卡正面
          bankCity: '', //开户行城市
          bankCode: '', //开户支行code
          bankName: '', //开户行名称
          bankNo: '', //结算卡号
          bankPhone: '', //银行预留手机号
          bankProvince: '', //开户行省份
          bankSubName: '', //开户支行名称
          fundAccountId: '', //资金帐号id
          id: '', //id，更新的时候传
          licence: '', //开户许可证
          settleBankType: '', //1 对公 2 对法人私
        }
      },
      //获取字典
      getAdminDict() {
        var dictType = "manage_settle_bank_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.settleMethodLs = res.result[0].dictList;
            this.settleMethodLs.splice(2, 2);
          })
      },
      getDetail() {
        getFundChangeSettle(this.fundAccountId).then(res => {
          const {
            result
          } = res
          //   this.ruleForm = result
          this.ruleForm = {
            bankRegionAvalue: [], //城市选择
            bankAccountName: result.bankAccountName, //结算账户名称
            bankCardBack: result.bankCardBack, //银行卡背面
            bankCardFront: result.bankCardFront, //银行卡正面
            bankCity: result.bankCity, //开户行城市
            bankCode: result.bankCode, //开户支行code
            bankName: result.bankName, //开户行名称
            bankNo: result.bankNo, //结算卡号
            bankPhone: result.bankPhone, //银行预留手机号
            bankProvince: result.bankProvince, //开户行省份
            bankSubName: result.bankSubName, //开户支行名称
            fundAccountId: result.fundAccountId, //资金帐号id
            id: result.id, //id，更新的时候传
            licence: result.licence, //开户许可证
            settleBankType: result.settleBankType, //1 对公 2 对法人私
          }
          //处理银行区域回显
          let bankRegionAvalue = [];
          bankRegionAvalue.push(res.result.bankProvince);
          bankRegionAvalue.push(res.result.bankCity);
          bankRegionAvalue.join(",");
          if (res.result.bankProvince != '') {
            // this.getBankBranchs();
            const params = {
              bankName: res.result.bankName,
              cityId: res.result.bankCity,
              provinceId: this.ruleForm.bankProvince
            };
            this.bankLoading = true
            getBankBranch(params).then((res) => {
                this.openAccBankLs = res.result
                // this.ruleForm.bankCode = res.result.bankCode
                this.bankLoading = false
                this.ruleForm.bankRegionAvalue = bankRegionAvalue;
              })
              .catch(() => {
                this.bankLoading = false
                // this.ruleForm.bankCode = ''
              });
          } else {
            this.ruleForm.bankRegionAvalue = [];
          }
          this.ruleForm.bankProvince = res.result.bankProvince;
          this.ruleForm.bankCity = res.result.bankCity
        })
      },
      getBankCitys() { //中台查询银盛城市
        let params = {}
        getBankCity(params).then((res) => {
          this.regionOptions = res.result;
          this.regionOptions.forEach((item) => {
            item.children.forEach((items) => {
              if (items.children.length == 0) {
                items.children = null
              }
            })
          })
        });
      },
      //银行区域选择
      bankRegionChange(value) {
        if (value.length == 0) {
          this.ruleForm.bankRegionAvalue = []
          this.openAccBankLs = []
          this.ruleForm.bankCode = '';
          this.ruleForm.bankSubName = '';
          return
        }
        this.ruleForm.bankProvince = value[0];
        this.ruleForm.bankCity = value[1];
        if (this.ruleForm.bankName == '') {
          this.$message.error('请输入开户行名称');
          this.ruleForm.bankRegionAvalue = []
          this.openAccBankLs = []
          return
        } else {
          this.getBankBranchs()
        }
        this.ruleForm.bankCode = '';
        this.ruleForm.bankSubName = '';
      },
      getBankBranchs() { //获取支行信息
        const params = {
          bankName: this.ruleForm.bankName,
          cityId: this.ruleForm.bankCity,
          provinceId: this.ruleForm.bankProvince
        };
        this.bankLoading = true
        getBankBranch(params).then((res) => {
            this.openAccBankLs = res.result
            this.bankLoading = false
          })
          .finally(() => {
            this.bankLoading = false
          });
      },
      branchChanges(id) {
        //支行选择
        console.log(id)
        this.openAccBankLs.map((item, index) => {
          if (id == item.bankCode) {
            this.ruleForm.bankCode = item.bankCode;
            this.ruleForm.bankSubName = item.bankName;
          }
        });
      },
      handleClose() { //关闭弹窗
        // this.$emit('update:visible', false)
        this.$refs['form'].resetFields();
        this.visible = false
      },
      getBankCardFront(e) { //获取结算银行卡正面
        console.log('e', e)
        if (e != '') {
          this.ruleForm.bankCardFront = e
        } else {
          this.ruleForm.bankCardFront = ''
        }
        this.$refs['bankCardFrontRef'].clearValidate();
      },
      getBankCardBack(e) { //获取结算银行卡背面
        console.log('e', e)
        if (e != '') {
          this.ruleForm.bankCardBack = e
        } else {
          this.ruleForm.bankCardBack = ''
        }
        this.$refs['bankCardBackRef'].clearValidate();
      },
      getLicence(e) { //获取开户许可证
        console.log('e', e)
        if (e != '') {
          this.ruleForm.licence = e
        } else {
          this.ruleForm.licence = ''
        }
        this.$refs['licenceRef'].clearValidate();
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.submitLoading = true
            this.ruleForm.fundAccountId = this.fundAccountId
            var data = {
              ...this.ruleForm
            }
            console.log('this.ruleForm.id', this.ruleForm.id)
            if (this.ruleForm.id == '') {
              fundChangeSettle(data).then(response => {
                this.$message.success('操作成功');
                setTimeout(() => {
                  this.handleClose()
                  this.$emit('success')
                  this.submitLoading = false
                }, 800)
              }).catch(() => {
                this.submitLoading = false
              });
            } else {
              updateFundChangeSettle(data).then(response => {
                this.$message.success('操作成功');
                setTimeout(() => {
                  this.handleClose()
                  this.$emit('success')
                  this.submitLoading = false
                }, 800)
              }).catch(() => {
                this.submitLoading = false
              });
            }

          }
        });
      },
    }
  }

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
    }

    .grid-layout {
      width: 560px;
      margin: 0 auto;
    }

    .img {
      display: block;
      width: 100px;
      height: auto;
    }
  }

  .max_title {
    font-size: 18px;
    color: #1890ff;
    font-weight: 600;
    height: 40px;
    line-height: 40px;
    border-bottom: 3px solid #1890ff;
    width: 750px;
    margin-bottom: 20px;
  }

  .el-input {
    width: 300px;
  }

  .el-select {
    width: 300px;
  }

  .dialog-footer .el-button {
    margin: 0 10px !important;
  }

  ::v-deep .el-upload {
    height: 148px !important;
  }

</style>
